package com.jack.thinking.thread.core._3;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedStreamCommuniaction {
	public static void main(String[] args) throws IOException {
		PipedInputStream pi = new PipedInputStream();
		PipedOutputStream po = new PipedOutputStream();
		pi.connect(po);
		ReadStream rs = new ReadStream(pi);
		OutStream os = new OutStream(po);
		rs.start();
		os.start();
		
	}
}

class ReadStream extends Thread{
	byte[] bs = new byte[20];
	
	private PipedInputStream pi;
	
	public ReadStream(PipedInputStream pi) {
		this.pi = pi;
	}
	
	@Override
	public void run() {
		try {
			int read = 0;
			read = pi.read(bs);
			while(read != -1) {
				String str = new String(bs, 0, read);
				System.out.println("--" +str);
				read = pi.read(bs);
			}
			//System.out.println(Arrays.toString(bs));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				pi.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

class OutStream extends Thread{
	byte[] bs = new byte[100];
	
	private PipedOutputStream po;
	
	public OutStream(PipedOutputStream po) {
		this.po = po;
	}
	
	@Override
	public void run() {
		for (int i = 0; i < bs.length; i++) {
			bs[i] = (byte) i;
		}
		try {
			po.write(bs, 0, bs.length);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				po.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
